﻿using System.Windows.Forms;
using System.Management;
using System.IO;
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml.Serialization;
using System.Reflection;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;
using System.Drawing;

namespace THenu.WMI.IPConfiguration
{
    partial class FrmMain : Form
    {
        #region 窗体特效代码
        /// <summary>
        /// 初始化窗体边框阴影效果
        /// </summary>
        const int CS_DropSHADOW = 0x20000;
        const int GCL_STYLE = (-26);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassLong(IntPtr hwnd, int nIndex);
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HTCAPTION = 0x2;
        /// <summary>
        /// 发送窗体消息
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="Msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        /// <summary>
        /// 标记系统窗体开始移动
        /// </summary>
        /// <returns></returns>
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        /// <summary>
        /// 窗体拖动代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
        }
        /// <summary>
        /// 窗体逐渐显示动画
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="dwTime"></param>
        /// <param name="dwFlags"></param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        protected static extern bool AnimateWindow(IntPtr hWnd, int dwTime, int dwFlags);
        public const Int32 AW_BLEND = 0x00080000;
        public const Int32 AW_CENTER = 0x00000010;
        public const Int32 AW_ACTIVATE = 0x00020000;
        public const Int32 AW_HIDE = 0x00010000;
        public const Int32 AW_SLIDE = 0x00040000;
        #endregion

        #region 常量和变量
        /// <summary>
        /// 当前操作的配置项
        /// </summary>
        private Guid _CurrentId = Guid.Empty;
        /// <summary>
        /// 响应用户
        /// </summary>
        private bool IsRespond = false;
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private string ConfigFilePath = string.Empty;
        /// <summary>
        /// 缓存本机网卡信息
        /// </summary>
        private List<ManagementObject> _NetCards = new List<ManagementObject>();
        /// <summary>
        /// 用户配置
        /// </summary>
        private List<IPConfiguration> ConfigurationList = new List<IPConfiguration>();
        /// <summary>
        /// 默认消息
        /// </summary>
        private string DeafultString = "   .   .   .";
        #endregion

        public static bool CreateNew = false;

        private static Mutex mutexLock;

        #region 初始化和加载
        /// <summary>
        /// 初始化和加载
        /// </summary>


        public static Mutex MutexLock
        {
            get
            {
                if (mutexLock == null)
                    return new Mutex(true, "THenu.WMI.IPConfiguration", out CreateNew);
                return mutexLock;
            }
        }
        public FrmMain()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            GenerateConfigFile();

            

            // API函数加载，实现窗体边框阴影效果
            SetClassLong(this.Handle, GCL_STYLE, GetClassLong(this.Handle, GCL_STYLE) | CS_DropSHADOW);

            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);

            // 调用示例 == 在Load事件中调用使窗体逐渐显示  ( 可修改效果组合)
            AnimateWindow(this.Handle, 500, AW_BLEND | AW_CENTER | AW_ACTIVATE);
        }
        /// <summary>
        /// 检查并生成配置
        /// </summary>
        private void GenerateConfigFile()
        {
            // 创建应用程序路径
            string userApplicationPath = MYLog.PathDirectory;
            ConfigFilePath = string.Format("{0}\\IPConfig.xml", MYLog.PathDirectory);

            if (!Directory.Exists(userApplicationPath))
            {
                Directory.CreateDirectory(userApplicationPath);
            }
            if (File.Exists(ConfigFilePath))
            {
                ReadUserConfiguration();
            }

        }
        /// <summary>
        /// 从本机读取配置
        /// </summary>
        private void ReadUserConfiguration()
        {

            try
            {
                XmlSerializer xmlIO = new XmlSerializer(typeof(List<IPConfiguration>));
                using (StringReader fileConfig = new StringReader(File.ReadAllText(ConfigFilePath)))
                {
                    ConfigurationList = xmlIO.Deserialize(fileConfig) as List<IPConfiguration>;
                    fileConfig.Close();
                }

                IsRespond = false;
                bindingSourceIP.DataSource = ConfigurationList;

                lbIPConfig.SelectedIndex = -1;
                IsRespond = true;
            }
            catch
            {
                UpdateToolStautsMessage("在读取用户配置时，发生了错误...", LogType.Waring);
            }

        }
        /// <summary>
        /// 获取当前的IP设置
        /// </summary>
        public IPConfiguration ReadCurrentIPConfiguration(bool display = false)
        {
            // 使用WMI获取本地计算机的网络设置
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                {
                    if (mo["Description"].ToString() == cbHardWareList.SelectedItem.ToString())
                    {
                        IPConfiguration configCurrent = new IPConfiguration();

                        configCurrent.ConfigId = Guid.Empty;
                        configCurrent.AliasName = "当前配置";

                        if (Convert.ToBoolean(mo["DHCPEnabled"]))
                        {
                            configCurrent.AliasName = "当前配置【自动获取】";
                        }
                        // 当前的地址
                        string[] ipAddress = (string[])mo["IPAddress"];
                        configCurrent.Address = ipAddress[0];
                        // 子网掩码
                        string[] iPSubnet = (string[])mo["IPSubnet"];
                        configCurrent.MaskAddress = iPSubnet[0];
                        // 网关
                        string[] newGateway = (string[])mo.GetPropertyValue("DefaultIPGateway");
                        configCurrent.GateWayAddress = newGateway[0];

                        // 将要修改的目标 DNS 首选地址 备用地址
                        string[] newDNS = (string[])mo.GetPropertyValue("DNSServerSearchOrder");
                        configCurrent.DNSAddress = newDNS[0];
                        configCurrent.DNSAddressPre = newDNS[1];


                        txtCurrentIP.Text = GetFormatIPAddress(ipAddress[0]);

                        if (display)
                        {
                            _CurrentId = Guid.Empty;
                            DisplayConfiguration(configCurrent);
                        }



                        return configCurrent;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 获取可以转换的格式
        /// </summary>
        /// <param name="stringAddress"></param>
        /// <returns></returns>
        private string GetNumberFormat(string stringAddress)
        {
            string result = string.Empty;
            string[] values = stringAddress.Split('.');
            foreach (var item in values)
            {
                result += item.Trim() + '.';
            }
            return result.TrimEnd('.');
        }
        /// <summary>
        /// 获取适应控件的格式字符串
        /// </summary>
        /// <param name="addressSource"></param>
        /// <returns></returns>
        private string GetFormatIPAddress(string addressSource)
        {
            if (string.IsNullOrEmpty(addressSource))
                return string.Empty;
            string strResult = string.Empty;
            string[] dnsPart1 = addressSource.Split('.');
            for (int i = 0; i <= 3; i++)
            {
                strResult += dnsPart1[i].PadLeft(3);
            }
            return strResult;
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, System.EventArgs e)
        {
            try
            {
                IsRespond = false;

                ReadNetConfigStatus();

                timerToolMSG.Enabled = true;
                timerToolMSG.Stop();

                lblStatusMSG.Text = "Make by 可爱可欣";
                lblStatusMSG.ForeColor = Color.DeepPink;
                IsRespond = true;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        /// <summary>
        /// 读取网络设置情况
        /// </summary>
        private void ReadNetConfigStatus()
        {
            // 使用WMI获取本地计算机的网络设置
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                {
                    _NetCards.Add(mo);
                    cbHardWareList.Items.Add(mo["Description"].ToString());
                }
            }

            if (cbHardWareList.Items.Count > 0)
            {
                cbHardWareList.SelectedIndex = 0;

                ReadCurrentIPConfiguration(true);
            }
            // 读取网络代理设置情况
            GetNetAgentStatus();
        }
        /// <summary>
        /// 读取网络代理设置情况
        /// </summary>
        private void GetNetAgentStatus()
        {
            Microsoft.Win32.RegistryKey br = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            // 打开注册表键 
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            try
            {


                if (rk.GetValue("ProxyEnable").ToString() == "1")
                {
                    string address = rk.GetValue("ProxyServer").ToString();
                    if (!string.IsNullOrEmpty(address))
                    {
                        string[] parts = address.Split(':');
                        //设置代理IP和端口 
                        maskedtxtAgent.Text = GetFormatIPAddress(parts[0]);
                        txtPort.Text = parts[1];
                    }
                    BtnDisabled.Text = "禁用代理";
                    BtnAgentEnable.Text = "已启用IE代理";
                    BtnAgentEnable.BackColor = Color.Green;
                }
                else
                {

                    BtnDisabled.Text = "启用代理";
                    BtnAgentEnable.Text = "已禁用用IE代理";
                    BtnAgentEnable.BackColor = Color.Red;
                }
            }
            catch (Exception ex)
            {

                MYLog.Error(ex.Message);
            }
            finally
            {
                rk.Close();
            }
        }
        #endregion

        #region 用户事件
        /// <summary>
        /// 应用设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnConfigured_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (lbIPConfig.SelectedItem == null)
                {
                    MessageBox.Show("请选择配置方案!");
                    return;
                }
                SendBackGroudwork("正在应用设置", TaskList.Apply, lbIPConfig.SelectedItem);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 设置自动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAuto_Click(object sender, System.EventArgs e)
        {
            try
            {

                SendBackGroudwork("正在应用设置", TaskList.Auto);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


        /// <summary>
        /// 获取当前选中网卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbHardWareList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            try
            {

                CurrentNetCard = cbHardWareList.SelectedItem.ToString().Trim();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 新增配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAppend_Click(object sender, System.EventArgs e)
        {
            try
            {
                txtAliasName.Text = string.Empty;
                mtxtIPAddress.Text = string.Empty;
                mtxtGateway.Text = string.Empty;
                mtxtSubNetwork.Text = string.Empty;
                mtxtDNSAddress.Text = string.Empty;
                mtxtDNSAddressPre.Text = string.Empty;

                txtAliasName.ReadOnly = false;
                mtxtIPAddress.ReadOnly = false;
                mtxtSubNetwork.ReadOnly = false;
                mtxtGateway.ReadOnly = false;

                _CurrentId = Guid.NewGuid();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelete_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (lbIPConfig.SelectedIndex > -1)
                {
                    ConfigurationList.RemoveAll(p => p.ConfigId.Equals(_CurrentId));

                    SendBackGroudwork("正在更新", TaskList.Delete);

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        #endregion

        #region 应用IP设置
        /// <summary>
        /// 设置自动获取
        /// </summary>
        private void AutoEnableDHCP()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                {
                    // 只对当前网卡进行设置
                    if (mo["Description"].ToString() == CurrentNetCard)
                    {
                        // 修改网络设置
                        //重置DNS为空  
                        mo.InvokeMethod("SetDNSServerSearchOrder", null);
                        //开启DHCP  
                        mo.InvokeMethod("EnableDHCP", null);
                        //mo.InvokeMethod("EnableStatic", null);
                        //mo.InvokeMethod("SetGateways", null);
                    }
                }
            }
        }
        /// <summary>
        /// 应用设置
        /// </summary>
        /// <param name="config"></param>
        private void ApplyIPConfiguration(IPConfiguration config)
        {
            // 应用设置
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                {
                    // 只对当前网卡进行设置
                    if (mo["Description"].ToString() == CurrentNetCard)
                    {
                        // 将要修改的目标 IP 地址
                        ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
                        newIP["IPAddress"] = new string[] { config.Address };
                        // 将要修改的目标子网掩码
                        newIP["SubnetMask"] = new string[] { config.MaskAddress };

                        // 将要修改的目标网关
                        ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
                        newGateway["DefaultIPGateway"] = new string[] { config.GateWayAddress };

                        // 将要修改的目标 DNS 首选地址 备用地址
                        ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        newDNS["DNSServerSearchOrder"] = new string[] { config.DNSAddress, config.DNSAddressPre };

                        // 修改网络设置
                        ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
                        ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGateway, null);
                        ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
        #endregion

        #region 保存用户配置
        /// <summary>
        /// 保存方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                #region 输入检查
                if (string.IsNullOrEmpty(txtAliasName.Text.Trim()))
                {
                    MessageBox.Show("请输入容易分辨的名称吧!☺");
                    return;
                }
                if (string.IsNullOrEmpty(mtxtIPAddress.Text.Trim()))
                {
                    MessageBox.Show("IP 地址不能为空哟!☺");
                    return;
                }
                IPAddress addressValue = null;
                IPConfiguration currentConfig = ConfigurationList.Find(p => p.ConfigId.Equals(_CurrentId));
                // 不存在则创建新行
                if (currentConfig == null)
                {
                    currentConfig = new IPConfiguration();
                    currentConfig.ConfigId = Guid.NewGuid();
                    ConfigurationList.Add(currentConfig);
                }
                currentConfig.AliasName = txtAliasName.Text.Trim();
                if (IPAddress.TryParse(GetNumberFormat(mtxtIPAddress.Text), out addressValue))
                {
                    currentConfig.Address = addressValue.ToString();
                }
                else if (!mtxtIPAddress.Text.Equals(DeafultString))
                {
                    MessageBox.Show("地址格式错误了! (>^ω^<)");
                    return;
                }
                if (IPAddress.TryParse(GetNumberFormat(mtxtSubNetwork.Text), out addressValue))
                {
                    currentConfig.MaskAddress = addressValue.ToString();
                }
                else if (!mtxtSubNetwork.Text.Equals(DeafultString))
                {
                    MessageBox.Show("地址格式错误了! (>^ω^<)");
                    return;
                }
                if (IPAddress.TryParse(GetNumberFormat(mtxtGateway.Text), out addressValue))
                {
                    currentConfig.GateWayAddress = addressValue.ToString();
                }
                else if (!mtxtGateway.Text.Equals(DeafultString))
                {
                    MessageBox.Show("地址格式错误了! (>^ω^<)");
                    return;
                }
                if (IPAddress.TryParse(GetNumberFormat(mtxtDNSAddress.Text), out addressValue))
                {
                    currentConfig.DNSAddress = addressValue.ToString();
                }
                else if (!mtxtDNSAddress.Text.Equals(DeafultString))
                {
                    MessageBox.Show("地址格式错误了! (>^ω^<)");
                    return;
                }
                if (IPAddress.TryParse(GetNumberFormat(mtxtDNSAddressPre.Text), out addressValue))
                {
                    currentConfig.DNSAddressPre = addressValue.ToString();
                }
                else if (!mtxtDNSAddressPre.Text.Equals(DeafultString))
                {
                    MessageBox.Show("地址格式错误了! (>^ω^<)");
                    return;
                }
                #endregion

                SendBackGroudwork("正在保存设置", TaskList.Save);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 保存设置到文件
        /// </summary>
        private bool SaveConfigToFile()
        {
            bool saveAll = true;
            try
            {
                XmlSerializer xmlIO = new XmlSerializer(typeof(List<IPConfiguration>));

                using (FileStream fileConfig = File.Create(ConfigFilePath))
                {
                    xmlIO.Serialize(fileConfig, ConfigurationList);
                    fileConfig.Close();
                }

                // 刷新数据显示
                bindingSourceIP.DataSource = ConfigurationList;
                bindingSourceIP.ResetBindings(false);
            }
            catch
            {
                saveAll = false;
            }


            return saveAll;

        }

        /// <summary>
        /// 刷新当前设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                ReadCurrentIPConfiguration();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 切换IP设置显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbIPConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lbIPConfig.SelectedIndex > -1 && IsRespond)
                {
                    IPConfiguration model = lbIPConfig.SelectedItem as IPConfiguration;
                    DisplayConfiguration(model);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        /// <summary>
        /// 显示配置信息
        /// </summary>
        /// <param name="model"></param>
        private void DisplayConfiguration(IPConfiguration model)
        {
            if (model != null)
            {
                _CurrentId = model.ConfigId;
                txtAliasName.Text = model.AliasName;
                mtxtIPAddress.Text = GetFormatIPAddress(model.Address);
                mtxtSubNetwork.Text = GetFormatIPAddress(model.MaskAddress);
                mtxtGateway.Text = GetFormatIPAddress(model.GateWayAddress);
                mtxtDNSAddress.Text = GetFormatIPAddress(model.DNSAddress);
                mtxtDNSAddressPre.Text = GetFormatIPAddress(model.DNSAddressPre);

                // 
                if (model.ConfigId == Guid.Empty)
                {
                    txtAliasName.ReadOnly = true;
                    mtxtIPAddress.ReadOnly = true;
                    mtxtSubNetwork.ReadOnly = true;
                    mtxtGateway.ReadOnly = true;
                    BtnDelete.Enabled = false;
                }
                else
                {
                    txtAliasName.ReadOnly = false;
                    mtxtIPAddress.ReadOnly = false;
                    mtxtSubNetwork.ReadOnly = false;
                    mtxtGateway.ReadOnly = false;
                    mtxtDNSAddress.ReadOnly = false;

                    mtxtDNSAddressPre.ReadOnly = false;
                    BtnDelete.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 控制显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbIPConfig_Format(object sender, ListControlConvertEventArgs e)
        {
            try
            {
                e.Value = (e.ListItem as IPConfiguration).AliasName;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 线程任务
        /// <summary>
        /// 通知执行任务
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="taskType"></param>
        /// <param name="mUserData"></param>
        private void SendBackGroudwork(string msg, TaskList taskType, object mUserData = null)
        {
            tableLayoutPanelMain.Enabled = false;
            timerToolMSG.Start();
            msgToolStatus = msg;
            bgExecuteWorker.RunWorkerAsync(new CallArgument() { CallType = taskType, UserData = mUserData });
        }
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgExecuteWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                CallArgument myCallData = (CallArgument)e.Argument;
                TaskList taskType = myCallData.CallType;
                e.Result = myCallData;
                switch (taskType)
                {
                    case TaskList.Apply:
                        ApplyIPConfiguration((IPConfiguration)myCallData.UserData);
                        break;
                    case TaskList.Delete:
                    case TaskList.Save:
                        myCallData.UserData = SaveConfigToFile();
                        break;
                    case TaskList.Auto:
                        AutoEnableDHCP();
                        break;
                    case TaskList.Enable:
                        myCallData.UserData = EnableIEAgent(myCallData.UserData.ToString());
                        break;
                    case TaskList.Disable:
                        myCallData.UserData = DisableIEAgnet();
                        break;
                }

            }
            catch (Exception ex)
            {
                MYLog.Error(ex.Message);
            }
        }
        /// <summary>
        /// 操作完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgExecuteWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            try
            {
                timerToolMSG.Stop();

                if (e.Cancelled)
                {
                    UpdateToolStautsMessage("操作被取消！");
                    return;
                }
                if (e.Error != null)
                {
                    UpdateToolStautsMessage("用户操作失败！");
                }
                else
                {
                    CallArgument myCallData = (CallArgument)e.Result;
                    TaskList taskType = myCallData.CallType;
                    switch (taskType)
                    {
                        case TaskList.Apply:
                            UpdateToolStautsMessage(" 设置应用完成");
                            break;
                        case TaskList.Save:
                            {
                                if (Convert.ToBoolean(myCallData.UserData))
                                {

                                    bindingSourceIP.ResetBindings(false);
                                    if (lbIPConfig.Items.Count > 0)
                                        lbIPConfig.SelectedIndex = lbIPConfig.Items.Count - 1;

                                    UpdateToolStautsMessage("保存成功");
                                    MessageBox.Show("保存成功！");

                                }
                                else
                                {

                                    UpdateToolStautsMessage("保存失败", LogType.Error);
                                    MessageBox.Show("保存失败！");
                                }
                            }
                            break;
                        case TaskList.Delete:
                            {
                                UpdateToolStautsMessage("删除成功");
                                bindingSourceIP.ResetBindings(false);
                                if (lbIPConfig.Items.Count > 0)
                                    lbIPConfig.SelectedIndex = lbIPConfig.Items.Count - 1;
                            }

                            break;
                        case TaskList.Auto:
                            UpdateToolStautsMessage("自动设置保存成功");
                            break;
                        case TaskList.Enable:
                            {
                                GetNetAgentStatus();
                                if (Convert.ToBoolean(myCallData.UserData))
                                {


                                    UpdateToolStautsMessage("IE代理设置成功");
                                }
                                else
                                {

                                    UpdateToolStautsMessage("IE代理设置失败", LogType.Error);
                                    MessageBox.Show("代理设置败！");
                                }
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                tableLayoutPanelMain.Enabled = true;
            }
        }
        #endregion

        #region 消息更新
        /// <summary>
        /// 更新消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerToolMSG_Tick(object sender, EventArgs e)
        {
            try
            {
                toolStripStatusLabel1.Text = string.Empty;
                recursionCount++;
                if (recursionCount == 1)
                {
                    UpdateToolStautsMessage(msgToolStatus + " .");
                }
                if (recursionCount == 2)
                {
                    UpdateToolStautsMessage(msgToolStatus + " . .");
                }
                if (recursionCount == 3)
                {
                    UpdateToolStautsMessage(msgToolStatus + " . . .");
                    recursionCount = -1;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 更新消息栏内容
        /// </summary>
        /// <param name="msgContent"></param>
        protected void UpdateToolStautsMessage(string msgContent)
        {
            UpdateToolStautsMessage(msgContent, LogType.Info);
        }
        /// <summary>
        /// 更新消息栏内容
        /// </summary>
        /// <param name="msgContent"></param>
        /// <param name="type"></param>
        protected void UpdateToolStautsMessage(string msgContent, LogType type)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new UpdateToolStatusDelegate(UpdateToolStautsMessage), new object[] { msgContent, type });
            }
            if (type == LogType.Error)
                lblStatusMSG.ForeColor = Color.Red;
            else
                lblStatusMSG.ForeColor = Color.Black;
            lblStatusMSG.Text = msgContent;
        }
        /// <summary>
        /// 消息委托
        /// </summary>
        /// <param name="msgContent"></param>
        /// <param name="type"></param>
        delegate void UpdateToolStatusDelegate(string msgContent, LogType type);
        /// <summary>
        /// 更新计数
        /// </summary>
        private volatile int recursionCount = 0;
        /// <summary>
        /// 默认的用户消息
        /// </summary>
        private volatile string msgToolStatus = "正在应用设置";
        /// <summary>
        /// 当前的网卡描述
        /// </summary>
        private string CurrentNetCard = string.Empty;
        #endregion

        #region IE代理设置
        /// <summary>
        /// 启用IE服务器代理
        /// </summary>
        /// <param name="hInternet"></param>
        /// <param name="dmOption"></param>
        /// <param name="lpBuffer"></param>
        /// <param name="dwBufferLength"></param>
        /// <returns></returns>
        [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "InternetSetOption", CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption(int hInternet, int dmOption, IntPtr lpBuffer, int dwBufferLength);
        /// <summary>
        /// 启用代理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAgentEnable_Click(object sender, EventArgs e)
        {
            try
            {
                // IP地址和端口
                string address = GetNumberFormat(maskedtxtAgent.Text) + ":" + txtPort.Text.Trim();
                msgToolStatus = "正在启用IE代理";
                bgExecuteWorker.RunWorkerAsync(new CallArgument() { CallType = TaskList.Enable, UserData = address });
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 启用IE代理
        /// </summary>
        private bool EnableIEAgent(string address)
        {
            bool result = true;
            // 打开注册表键 
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            try
            {
                if (rk.GetValue("ProxyEnable").ToString() == "0")
                {
                    //设置代理可用 
                    rk.SetValue("ProxyEnable", 1);

                    if (!string.IsNullOrEmpty(address))
                    {
                        //设置代理IP和端口 
                        rk.SetValue("ProxyServer", address);
                    }
                }
                else
                {
                    rk.SetValue("ProxyEnable", 0);
                }
            }
            catch (Exception ex)
            {
                result = false;
                MYLog.Error(ex.Message);
            }
            finally
            {
                rk.Close();
                //激活代理设置
                InternetSetOption(0, 39, IntPtr.Zero, 0);
                InternetSetOption(0, 37, IntPtr.Zero, 0);
            }

            return result;
        }
        /// <summary>
        /// 只响应数据键盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                // 特殊键盘字符
                if (Convert.ToInt32(e.KeyChar) <= 36)
                {
                    return;
                }
                if (!Char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 禁用IE代理
        /// </summary>
        private bool DisableIEAgnet()
        {
            bool result = true;
            // 打开注册表键 
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            try
            {

                rk.SetValue("ProxyEnable", 0);

            }
            catch (Exception ex)
            {
                result = false;
                MYLog.Error(ex.Message);
            }
            finally
            {
                rk.Close();
                //激活代理设置
                InternetSetOption(0, 39, IntPtr.Zero, 0);
                InternetSetOption(0, 37, IntPtr.Zero, 0);
            }

            return result;
        }
        #endregion

        #region IP 显示框的用户事件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCurrentIP_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ReadCurrentIPConfiguration(true);
        }
        #endregion

    }
    /// <summary>
    /// 任务分类
    /// </summary>
    public enum TaskList
    {
        None,
        Apply,
        Auto,
        Save,
        Delete,
        Enable,
        Disable
    }
    /// <summary>
    /// 传递调用的参数
    /// </summary>
    public class CallArgument
    {
        /// <summary>
        /// 类型
        /// </summary>
        public TaskList CallType { get; set; }
        /// <summary>
        /// 用户数据
        /// </summary>
        public object UserData { get; set; }
    }

}